package com.dili.dd.gpi.service.impl;

import com.dili.dd.gpi.domain.Site;
import com.dili.dd.gpi.domain.SiteExample;
import com.dili.dd.gpi.mapper.SiteMapper;
import com.dili.dd.gpi.service.SiteService;
import com.dili.dd.gpi.util.spring.DataSourceLookupKey;
import com.dili.dd.gpi.util.spring.RequireDataSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by zhaoYuan on 2015/10/19.
 */
@Service
public class SiteServiceImpl implements SiteService {

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Resource
    private SiteMapper siteMapper;

    @Override
    @RequireDataSource(key = DataSourceLookupKey.GPI_DATASOURCE)
    @Transactional(readOnly = false,propagation = Propagation.SUPPORTS)
    public Site get(int id) {
        return siteMapper.selectByPrimaryKey(id);
    }

    @Override
    @RequireDataSource(key = DataSourceLookupKey.GPI_DATASOURCE)
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void createSite(Site site) {
        site.setDeleted(false);
        Date now = new Date();
        site.setCreateTime(now);
        site.setUpdateTime(now);
        siteMapper.insert(site);
    }

    @Override
    @RequireDataSource(key = DataSourceLookupKey.GPI_DATASOURCE)
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void updateSite(Site site) {
        Date now = new Date();
        site.setUpdateTime(now);
        siteMapper.updateByPrimaryKeySelective(site);
    }

    @Override
    @RequireDataSource(key = DataSourceLookupKey.GPI_DATASOURCE)
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void deleteSite(int siteId) {
        Site site = siteMapper.selectByPrimaryKey(siteId);
        site.setDeleted(true);
        site.setUpdateTime(new Date());
        siteMapper.updateByPrimaryKeySelective(site);
    }

    @Override
    @RequireDataSource(key = DataSourceLookupKey.GPI_DATASOURCE)
    @Transactional(readOnly = false,propagation = Propagation.SUPPORTS)
    public List<Site> findAll() {
        SiteExample example = new SiteExample();
        example.createCriteria().andDeletedEqualTo(false);
        example.setOrderByClause("update_time");
        return siteMapper.selectByExample(example);
    }
}
